package com.example.productserver.interceptor;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import com.example.productserver.common.constant.RedisKeyPrefixConst;
import com.example.productserver.filter.CustomHttpServletRequestWrapper;
import com.example.productserver.menu.StatusCode;
import com.example.productserver.result.ResultBase;
import com.example.productserver.util.BloomRedisService;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class BloomFilterInterceptor implements HandlerInterceptor{

    @Autowired
    private BloomRedisService bloomRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper)request;
        String body = wrapper.getBody();

        JSONObject json = JSON.parseObject(body);
        String pid = json.getInteger("id").toString();

        //布隆过滤器存储在redis中
        if(bloomRedisService.includeByBloomFilter(RedisKeyPrefixConst.PRODUCT_REDIS_BLOOM_FILTER,pid)){
            return true;
        }
        resultBase(response);
        return false;


    }

    private void resultBase(HttpServletResponse response) throws IOException {
        ResultBase res = new ResultBase();
        res.setSuccess(false);
        res.setMessage("商品不存在");
        res.setCode(StatusCode.ERROR);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().write(JSON.toJSONString(res));
        response.getWriter().flush();
    }

}
